package com.xiaolu.qqclient.view;

import com.xiaolu.qqclient.service.FileClientService;
import com.xiaolu.qqclient.service.MessageClientService;
import com.xiaolu.qqclient.service.UserClientService;
import com.xiaolu.qqclient.test.AudioClient;
import com.xiaolu.qqcommon.Message;

import javax.sound.sampled.*;
import javax.swing.*;
import java.awt.*;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class ChatRoomGUI extends JFrame {

    public List<Message> historyMessages = new ArrayList<>();
    private static ChatRoomGUI instance = null;  // 单例实例
    private ByteArrayOutputStream audioData;
    private JPanel chatPanel;
    private JScrollPane chatScrollPane;
    private JTextArea inputArea;
    private JButton sendButton;
    private JList<String> onlineUserList;
    private JButton voiceButton;
    private boolean isRecording = false;
    private ScheduledExecutorService scheduler;
    private int vbcnt = 1;

    private MessageClientService messageClientService = new MessageClientService();// 对象用户私聊/群聊.
    private FileClientService fileClientService = new FileClientService();// 该对象用户传输文件

    private void sendMessageToServer(String messageContent, String selectedUser, String currentUser) {
        if (selectedUser.equals("全部人")) {
            messageClientService.sendMessageToAll(messageContent, currentUser);
        } else {
            messageClientService.sendMessageToOne(messageContent, currentUser, selectedUser);
        }
    }

    private void recordVoice(boolean isRecording) {
        // 根据传入的isRecording判断录音什么时候结束
        // 这里没有具体实现******************************************************
        // 这里没有具体实现******************************************************
        // 这里没有具体实现******************************************************
        // 这里没有具体实现******************************************************
        // 这里没有具体实现******************************************************
        // 这里没有具体实现******************************************************
    }

    private void voicePlay(int voiceNum){
        //根据需要播放的语音编号寻找对应的语音
        System.out.println(voiceNum);
        //点击播放语音按钮播放语音
        // 播放录音
        new Thread(() -> {
            try {
                byte[] audioBytes =historyMessages.get(voiceNum-1).getVoiceData();
                ByteArrayInputStream bais = new ByteArrayInputStream(audioBytes);
                AudioFormat format = new AudioFormat(44100, 16, 2, true, true);
                DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);
                SourceDataLine line = (SourceDataLine) AudioSystem.getLine(info);
                line.open(format);
                line.start();

                System.out.println("正在播放录音...");
                byte[] buffer = new byte[4096];
                int bytesRead;

                while ((bytesRead = bais.read(buffer)) != -1) {
                    line.write(buffer, 0, bytesRead);
                }

                line.drain();
                line.close();
                System.out.println("录音播放结束。");

            } catch (IOException | LineUnavailableException e) {
                e.printStackTrace();
            }
        }).start();
    }
    //这里是发消息给别人的时候 自己的屏幕会显示发出去的内容
    private void displayReceivedMessage(String sender, String message, String selectUser) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = sdf.format(new Date());

        JPanel messagePanel = new JPanel();
        messagePanel.setLayout(new FlowLayout(FlowLayout.LEFT));
        messagePanel.setPreferredSize(new Dimension(chatPanel.getWidth(), 50));

        Font messageFont = new Font("SansSerif", Font.PLAIN, 16);
        JLabel messageLabel = new JLabel(time + " " + sender + " 对 " + selectUser + " 说: " + message);
        messageLabel.setFont(messageFont);
        messageLabel.setPreferredSize(new Dimension(400, 40));
        messagePanel.add(messageLabel);

        if (message.startsWith("语音")) {
            JButton voiceButton = new JButton("播放语音" + vbcnt);
            vbcnt++;
            Dimension buttonSize = new Dimension(100, 40);
            voiceButton.setPreferredSize(buttonSize);
            voiceButton.setMargin(new Insets(2, 5, 2, 5));
            messagePanel.add(voiceButton);

            voiceButton.addActionListener(e -> {
                String buttonText = voiceButton.getText();
                // 使用正则表达式提取数字部分
                String numberPart = buttonText.replaceAll("[^0-9]", "");
                System.out.println("播放语音，按钮编号：" + numberPart);
                int voiceNum = Integer.valueOf(numberPart);
                voicePlay(voiceNum);
                // 这里没有具体实现******************************************************
            });
        }

        chatPanel.add(messagePanel);
        chatPanel.revalidate();
        chatPanel.repaint();
        chatScrollPane.getVerticalScrollBar().setValue(chatScrollPane.getVerticalScrollBar().getMaximum());
    }

    // 接收到信息显示到界面
    public void displayReceivedMessage(String sender, String message) {
        System.out.println("收到信息了，message：" + message);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = sdf.format(new Date());

        JPanel messagePanel = new JPanel();
        messagePanel.setLayout(new FlowLayout(FlowLayout.LEFT));
        messagePanel.setPreferredSize(new Dimension(chatPanel.getWidth(), 50));

        Font messageFont = new Font("SansSerif", Font.PLAIN, 16);
        JLabel messageLabel = new JLabel(time + " " + sender + " 对 我 说: " + message);
        messageLabel.setFont(messageFont);
        messageLabel.setPreferredSize(new Dimension(400, 40));
        messagePanel.add(messageLabel);

        if (message.startsWith("语音")) {
            JButton voiceButton = new JButton("播放语音" + vbcnt);
            vbcnt++;
            Dimension buttonSize = new Dimension(100, 40);
            voiceButton.setPreferredSize(buttonSize);
            voiceButton.setMargin(new Insets(2, 5, 2, 5));
            messagePanel.add(voiceButton);

            voiceButton.addActionListener(e -> {
                String buttonText = voiceButton.getText();
                // 使用正则表达式提取数字部分
                String numberPart = buttonText.replaceAll("[^0-9]", "");
                System.out.println("播放语音，按钮编号：" + numberPart);
                int voiceNum = Integer.valueOf(numberPart);
                voicePlay(voiceNum);
                // 这里没有具体实现******************************************************
            });
        }

        chatPanel.add(messagePanel);
        chatPanel.revalidate();
        chatPanel.repaint();
        chatScrollPane.getVerticalScrollBar().setValue(chatScrollPane.getVerticalScrollBar().getMaximum());
    }

    private void sendVoiceData() {
        // 这里没有具体实现******************************************************
        // 这里没有具体实现******************************************************
        // 这里没有具体实现******************************************************
        // 这里没有具体实现******************************************************
        // 这里没有具体实现******************************************************
        // 这里没有具体实现******************************************************
    }

    // 私有构造函数，防止外部实例化
    ChatRoomGUI(String currentUser, UserClientService userClientService) {
        // 向服务器发送请求获取在线用户列表
        userClientService.onlineFriendList();

        // 启动定时任务，每隔3秒执行一次
        scheduler = Executors.newScheduledThreadPool(1);
        scheduler.scheduleAtFixedRate(() -> {
            // 在线好友列表的刷新逻辑
            userClientService.onlineFriendList();
        }, 0, 1, TimeUnit.SECONDS);

        // 开始显示聊天室页面
        setTitle("聊天室");
        setSize(800, 600);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JSplitPane mainSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
        mainSplitPane.setDividerLocation(200);

        JLabel onlineUserTitleLabel = new JLabel("在线用户列表");
        Font titleFont = new Font("SansSerif", Font.BOLD, 18);
        onlineUserTitleLabel.setFont(titleFont);
        onlineUserTitleLabel.setHorizontalAlignment(SwingConstants.CENTER);
        DefaultListModel<String> onlineUserListModel = new DefaultListModel<>();
        onlineUserList = new JList<>(onlineUserListModel);

        // 设置在线用户列表的字体大小
        Font listFont = new Font("SansSerif", Font.PLAIN, 16);
        onlineUserList.setFont(listFont);

        JScrollPane onlineUserScrollPane = new JScrollPane(onlineUserList);
        onlineUserScrollPane.setColumnHeaderView(onlineUserTitleLabel);
        onlineUserListModel.addElement("全部成员");
        onlineUserListModel.addElement("test");

        Dimension onlineUserSize = onlineUserScrollPane.getPreferredSize();
        onlineUserSize.width = 200;
        onlineUserScrollPane.setPreferredSize(onlineUserSize);

        mainSplitPane.setLeftComponent(onlineUserScrollPane);

        JPanel rightPanel = new JPanel();
        rightPanel.setLayout(new BorderLayout());

        chatPanel = new JPanel();
        chatPanel.setLayout(new BoxLayout(chatPanel, BoxLayout.Y_AXIS));
        chatScrollPane = new JScrollPane(chatPanel);
        chatScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

        inputArea = new JTextArea(3, 40);
        sendButton = new JButton("发送");
        voiceButton = new JButton("语音");

        JPanel inputPanel = new JPanel();
        inputPanel.setLayout(new BorderLayout());
        inputPanel.add(inputArea, BorderLayout.CENTER);
        inputPanel.add(voiceButton, BorderLayout.WEST);
        inputPanel.add(sendButton, BorderLayout.EAST);
        inputPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));

        rightPanel.add(chatScrollPane, BorderLayout.CENTER);
        rightPanel.add(inputPanel, BorderLayout.SOUTH);

        mainSplitPane.setRightComponent(rightPanel);

        add(mainSplitPane);

        sendButton.addActionListener(e -> {
            String messageContent = inputArea.getText();
            String selectedUser = onlineUserList.getSelectedValue();
            if (selectedUser!= null) {
                if (selectedUser.equals("全部人")) {
                    displayReceivedMessage("我", messageContent, "全部人");
                } else {
                    displayReceivedMessage("我", messageContent, selectedUser);

                }
                inputArea.setText("");
                sendMessageToServer(messageContent, selectedUser, currentUser);
            } else {
                JOptionPane.showMessageDialog(this, "请选择要发送的用户", "提示", JOptionPane.WARNING_MESSAGE);
            }
        });

        // 语音按钮逻辑
        AudioClient client = new AudioClient();
        voiceButton.addActionListener(e -> {
            String selectedUser = onlineUserList.getSelectedValue();
            if (selectedUser!= null) {
                // 开始录音
                client.startRecording();
                if (!isRecording) {
                    isRecording = true;
                    voiceButton.setText("录音中...");
                    recordVoice(isRecording);

                    voiceButton.setForeground(Color.RED);
                } else {
                    // 停止录音
                    client.stopRecordingAndPlay();


                    isRecording = false;
                    voiceButton.setText("语音");
                    voiceButton.setForeground(null);

                    if (selectedUser.equals("全部人")) {
                        displayReceivedMessage("我", "语音消息", "全部人");
                        for (int i = 1; i < onlineUserList.getModel().getSize(); i++) {
                            String item = onlineUserList.getModel().getElementAt(i);
                            System.out.println("debug"+item);
                            if (!item.equals(currentUser)){
                                // 给除了自己以外的所有用户发
                                client.sendRecording("127.0.0.1", 5000, currentUser, item);
                            }

                        }
                    } else {
                        displayReceivedMessage("我", "语音消息", selectedUser);
                        //发送私聊语音
                        client.sendRecording("127.0.0.1", 5000, currentUser, selectedUser);
                    }
                    recordVoice(isRecording);

                    sendVoiceData();
                }
            } else {
                JOptionPane.showMessageDialog(this, "请选择要发送的用户", "提示", JOptionPane.WARNING_MESSAGE);
            }
        });

        voiceButton.addActionListener(e -> {
            String buttonText = voiceButton.getText();
            System.out.println("语音按钮文本：" + buttonText);
        });
    }

    // 公共的静态方法，获取单例实例
    public static synchronized ChatRoomGUI getInstance(String currentUser, UserClientService userClientService) {
        if (instance == null) {
            instance = new ChatRoomGUI(currentUser, userClientService);
        }
        return instance;
    }

    public static synchronized ChatRoomGUI getInstance() {
        return instance;
    }

    public void updateOnlineUserList(String[] newOnlineUsers) {
        // 只有在列表不同的情况下，才进行更新
        if (!this.areListsEqual(newOnlineUsers, this.onlineUserList)) {
            DefaultListModel<String> onlineUserListModel = (DefaultListModel<String>) onlineUserList.getModel();
            onlineUserListModel.clear(); // 清空旧的在线用户列表
            onlineUserListModel.addElement("全部人"); // 添加固定的第一项
            for (String user : newOnlineUsers) {
                onlineUserListModel.addElement(user); // 逐个添加新的在线用户
            }
        }
    }

    public boolean areListsEqual(String[] list1, JList<String> list2) {
        ListModel<String> model2 = list2.getModel();

        // 先忽略 JList 中的第一项 "全部人"，因此比较时从第二项开始
        if (list1.length!= (model2.getSize() - 1)) {
            return false; // 如果长度不一致，直接返回 false
        }

        // 逐个比较数组和 JList 的元素（从第 2 项开始）
        for (int i = 0; i < list1.length; i++) {
            if (!list1[i].equals(model2.getElementAt(i + 1))) { // 跳过 JList 的第 1 项
                return false; // 只要有一个元素不同，返回 false
            }
        }

        return true; // 如果所有元素都相等，则返回 true
    }
}